package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"somedata/core"
	logger2 "somedata/logger"
	"somedata/store/model"
	"somedata/store/vo"
	"somedata/utils/resp"
)

var logger = logger2.GetLogger()

type LocationHandler struct {
	BaseHandler
	db *gorm.DB
}

func NewUserHandler(app *core.AppServer, db *gorm.DB) *LocationHandler {
	h := LocationHandler{db: db}
	h.App = app
	return &h
}

func (h *LocationHandler) List(c *gin.Context) {
	page := h.GetInt(c, "page", 1)
	pageSize := h.GetInt(c, "page_size", 20)
	level := h.GetTrim(c, "level")
	session := h.db.Session(&gorm.Session{})

	if level == "" {
		level = "province"
	}
	session = session.Where("level = ?", level).Order("created_at ASC")

	var items []model.Location
	var total int64

	offset := (page - 1) * pageSize
	session.Model(&model.Location{}).Count(&total)
	res := session.Offset(offset).Limit(pageSize).Find(&items)
	if res.Error != nil {
		logger.Info(res.Error.Error())
		resp.ERROR(c, "数据查询失败")
		return
	}

	//var locations = make([]vo.Location, 0)
	pageVo := vo.NewPage(total, page, pageSize, items)
	resp.SUCCESS(c, pageVo)
}
